#!/bin/bash

declare -r SCRIPT_DIR=$(dirname $(readlink -m "${BASH_SOURCE[0]}"))

function die()
{
    echo -e "\e[0;31m[ERROR]\e[m $1" >&2
    exit ${2:-255}
}

declare -r PROGNAME=$(basename $0)
options=`getopt -o 'ch' -n "$PROGNAME" -- "$@"` || die "Fail: getopt"
eval set -- "$options"
[ $? != 0 ] && die "Set options failed. Terminating..." 1

while true ; do
    case "$1" in
        -h) Usage;;
        -v) declare -g -x -r VERBOSE='on'; shift ;;
        -c) declare -g -x -r CLEAN_BUILD='-c'; shift ;;
        --) shift ; break ;;
        *) echo "Internal error!" ; exit 1 ;;
    esac
done

declare -r CMAKE_DIR="${SCRIPT_DIR}/cmake"
declare -r BUILD_DIR="${CMAKE_DIR}/build"

function clean()
{
    [ ! -d ${BUILD_DIR} ] || rm -rf ${BUILD_DIR:?bad BUILD_DIR} || die "Fail to remove ${BUILD_DIR}"
}

function do_build()
{
    mkdir -p "${BUILD_DIR:?bad BUILD_DIR}" || die "'mdkir -p ${BUILD_DIR}' failed"
    cd "${BUILD_DIR:?bad BUILD_DIR}"
    cmake "${VERBOSE+-DVERBOSE=on}" ..
    make
}

################################################################
# Main Process
################################################################

[ -n "${CLEAN_BUILD}" ] && clean
do_build

